package com.bawei.shopping2

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.CheckBox
import androidx.activity.viewModels
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.shopping2.adapter.CarGoodsAdapter
import com.bawei.shopping2.databinding.ActivityCarBinding
import com.bawei.shopping2.entity.CarGoodsEntity
import com.bawei.shopping2.http.ApiResponse
import com.bawei.shopping2.utils.ArouterPath
import com.bawei.shopping2.viewmodel.CarViewModel
import com.blankj.utilcode.util.ToastUtils
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

@AndroidEntryPoint
@Route(path = ArouterPath.ROUTE_CAR_PATH)
class CarActivity : AppCompatActivity() {
    private lateinit var activityCarBinding: ActivityCarBinding
    private lateinit var carGoodsAdapter: CarGoodsAdapter
    private var list = mutableListOf<CarGoodsEntity>()
    private val carViewModel:CarViewModel by viewModels()
    private var job = Job()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityCarBinding = ActivityCarBinding.inflate(layoutInflater)
        setContentView(activityCarBinding.root)
        initRv()
        CoroutineScope(job).launch(Dispatchers.Main){
            var apiResponse = carViewModel.selectCar()
            showCar(apiResponse)
        }

        //全选和取消全选
        activityCarBinding.cbAll.setOnCheckedChangeListener { buttonView, isChecked ->
            list.forEach {
                it.select = isChecked
            }
            carGoodsAdapter.notifyItemRangeChanged(0,list.size,"select")//从0数list.size个局部刷新：选中
            total()
        }
        //item子控件的点击
        carGoodsAdapter.onItemChildClick = { v: View, pos: Int->

            when(v.id){
                R.id.iv_delete -> {
                    ToastUtils.showLong("点击了删除")
                    list.removeAt(pos)
                    carGoodsAdapter.notifyItemRemoved(pos)//局部刷新：删除
                }
                R.id.iv_jia -> {
                    ToastUtils.showLong("点击了加")
                   var  num =  list[pos].count+1
                   list[pos].count = num
                    carGoodsAdapter.notifyItemChanged(pos,"carNum")//局部刷新：只刷新数量
                }
                R.id.iv_jian -> {
                    ToastUtils.showLong("点击了减")
                    var  num =  list[pos].count-1
                    list[pos].count = num
                    carGoodsAdapter.notifyItemChanged(pos,"carNum")//局部刷新：只刷新数量
                }
                R.id.cb -> {
                    ToastUtils.showLong("点击了复选框")
                    var cb:CheckBox = v as CheckBox//转成CheckBox
                    list[pos].select = cb.isChecked//获得选中还是没有选中
                    carGoodsAdapter.notifyItemChanged(pos,"select")
                }
            }
            total()
        }
        //删除选中的
        activityCarBinding.tvDelete.setOnClickListener{
            var ids = "" // 1,2,3,4,
            list.forEach {
                if(it.select){
                    Log.d("ytx", "onCreate: ${it.id}")
                    ids+=it.id
                    ids+=","
                }
            }
            Log.d("ytx", "选中的id11: $ids")
            ids = ids.substring(0,ids.length-1)
            Log.d("ytx", "选中的id22: $ids")
            var map = mutableMapOf<String,String>()
            map["ids"] = ids
            var requestBody = map.toBody()

            //使用协程网络请求：删除购物车
            CoroutineScope(job).launch (Dispatchers.Main){
               var apiResponse =  carViewModel.deleteCar(requestBody)
               showDelete(apiResponse)
            }





        }
    }
    //本地删除，
    private fun showDelete(apiResponse: ApiResponse<String>) {
        if(apiResponse.code == 200){
            //普通for循转 倒叙遍历
            for (i in list.size - 1 downTo 0) {
               if(list[i].select){
                   list.removeAt(i)
               }
            }
            carGoodsAdapter.notifyDataSetChanged()
        }
    }

    //计算总价和数量
    private fun total(){
        var money = 0
        var sum = 0
        list.forEach {
            if(it.select) {
                money += it.count*it.goods_default_price
                sum += it.count
            }
        }
        activityCarBinding.tvMoney.text = "总价:¥ $money"
        activityCarBinding.btAccount.text = "结算（$sum)"
    }




    private fun showCar(apiResponse: ApiResponse<MutableList<CarGoodsEntity>>) {
        if(apiResponse.code == 200){
            list.addAll(apiResponse.data)
            carGoodsAdapter.notifyDataSetChanged()
        }
    }

    private fun initRv() {
        carGoodsAdapter = CarGoodsAdapter(list)
        activityCarBinding.rv.adapter = carGoodsAdapter
        activityCarBinding.rv.layoutManager = LinearLayoutManager(this)
        activityCarBinding.rv.addItemDecoration(DividerItemDecoration(this,DividerItemDecoration.VERTICAL))
    }
}